define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'inventory/temporary/index' + location.search,
                    add_url: 'inventory/temporary/add',
                    edit_url: 'inventory/temporary/edit',
                    del_url: 'inventory/temporary/del',
                    multi_url: 'inventory/temporary/multi',
                    import_url: 'inventory/temporary/import',
                    table: 'temporary',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 3,
                showToggle:false,
                dblClickToEdit: false, //是否启用双击编辑，改为 false 即可。
                columns: [
                    [
                        {checkbox: true},
                      //  {field: 'id', title: __('Id')},
                        {field: 'source_code', title: __('Source_code'), operate: 'LIKE',formatter:function(val,row,i){
                        	if(row.order_list==2){
                        		return row.b_remark+' -> '+row.source_code
                        	}else{
								if(row.order_list == 16){
									return row.b_remark
								}else{
									return row.source_code
								}
                        	}
                        }},
                        {field: 'order_code', title: __('Order_code'), operate: 'LIKE'},
                        {field: 'order_list', title: __('Order_list'), searchList:orderListList, formatter: Table.api.formatter.normal,width:100},
                        {field: 'number', title: __('Number'), operate: 'LIKE',width:100},
                        {field: 'name', title: __('Name'), operate: 'LIKE',width:250},
                        {field: 'specification', title: __('Specification'), operate: 'LIKE',width:140},
                        {field: 'unit', title: __('Unit'), operate: 'LIKE',width:80},
						{field: 'store_unit', title: __('Store_unit'), operate: 'LIKE',width:80},
						{field: 'warehouse_name', title: __('Warehouse_name'), operate: 'LIKE',width:100},
                        {field: 'shelves_name', title: __('Shelves_name'), operate: 'LIKE',width:120},
                        //{field: 'shelves_type', title: __('Shelves_type'), searchList: shelvesTypeList, formatter: Table.api.formatter.normal,width:80},
                        //{field: 'warehouse_id', title: __('Warehouse_id')},
                       // {field: 'shelves_id', title: __('Shelves_id')},
					   {field: 'cBatch', title: __('cBatch'), operate: 'LIKE',width:100,formatter:function(val,row,i){
							var qrNo = ''
							if(row.qrNo!=null&&row.qrNo!=''){
								qrNo = '-'+row.qrNo+''
							}
							return row.cBatch+qrNo
						}},
                        //{field: 'grounding_list', title: __('Grounding_list'), searchList: groundingListList, formatter: Table.api.formatter.normal},
                        //{field: 'cName', title: __('cName'), operate: 'LIKE',width:120},
                        //{field: 'cItemCName', title: __('cItemCName'), operate: 'LIKE',width:120},
                        {field: 'u8_code', title: __('U8_code'), operate: 'LIKE',formatter:function(val,row,i){
							if(row.kis_work_incode!=null&&row.kis_work_incode!=''){
								return row.u8_code+','+row.kis_work_incode
							}
							return row.u8_code;
						}},
                        {field: 'result', title: __('Result'), operate: 'LIKE',width:200},
                        {field: 'pass_status', title: __('Pass_Status_list'), searchList: passStatusListList, formatter: function(val,row){
							if(row.order_list==1){
								return row.pass_status_list_text
							}
						},width:80},
						{field: 'kis_dbcode', title: __('Kis_dbcode'), operate: 'LIKE',width:150,formatter:function(val,row,i){
							if(row.order_list == 16 && row.kis_dbcode!=null){
								return '其他入库:'+row.kis_dbcode
							}
							return row.kis_dbcode
						}},
						{field: 'kis_work_outcode', title: __('Kis_work_outcode'),width:170, operate: 'LIKE',formatter:function(val,row,i){
							if(row.order_list == 16 && row.kis_work_outcode!=null){
								return '其他出库:'+row.kis_work_outcode
							}
							return row.kis_work_outcode
						}},
						{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,width:120},
                        {field: 'quantity', title: __('Quantity'), operate:'BETWEEN'},
						{field: 'store_quantity', title: __('Store_quantity'), operate:'BETWEEN'},
                        {field: 'status', title: __('Status_list'), searchList: statusListList, formatter: Table.api.formatter.normal,width:80},
						
                        //{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        /*{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        	formatter: function (value, row, index) {
                        		var that = $.extend({}, this);
                        		/*if(row.order_list==8||row.order_list==9){
                        			$(table).data("operate-edit", false); // 列表页面隐藏 .编辑operate-edit - 删除按钮operate-del
                        			that.table = table;
                        		}else{
                        			$(table).data("operate-edit", true);
                        		}*/
                        		/*$(table).data('operate-edit',null);
                        		return Table.api.formatter.operate.call(that,value,row,index)
                        	}
                        }*/
                    ]
                ]
            });

          //自定义Tab筛选条件
            $('.panel-heading .nav-custom-condition a[data-toggle="tab"]', table.closest(".panel-intro")).on('shown.bs.tab', function (e) {
                var value = $(this).data("value");
                var options = table.bootstrapTable('getOptions');
                var queryParams = options.queryParams;
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    //这一行必须要存在,否则在点击下一页时会丢失搜索栏数据
                    params = queryParams(params);
                    //如果希望追加搜索条件,可使用
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    var op = params.op ? JSON.parse(params.op) : {};
                    if (value) {
                        //这里可以自定义多个筛选条件
                    	/*switch(value){
	                    	case 1://入库相关
	                    		filter.order_list = '1,3,5,6,10';
	                    		op.order_list = 'in';
	                    		break;
	                    	case 2://出库相关
	                    		filter.order_list = '2,4,7,11,12';
	                    		op.order_list = 'in';
	                    		break;
	                    	case 3://调拨
	                    		filter.order_list = '8';
	                    		op.order_list = '=';
	                    		break;
	                    	case 4://盘点
	                    		filter.order_list = '9';
	                    		op.order_list = '=';
	                    		break;
	                    	case 5:
	                    		filter.order_list = ''
	                    		op.order_list = 'neq';
	                    		//$("[type='reset']").trigger('click')
	                    		break;
                    	}*/
                    	filter.order_list_tab = value
                    } else {
                        //选全部时要移除相应的条件
                        //delete filter.order_list;
                        //delete op.order_list;
                    }

                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);

                    //如果希望忽略搜索栏搜索条件,可使用
                    //params.filter = JSON.stringify(value?{admin_id: value}:{});
                    //params.op = JSON.stringify(value?{admin_id: '='}:{});
                    return params;
                };

                table.trigger("uncheckbox");
                table.bootstrapTable('refresh', {pageNumber: 1});
                return false;
            });
            
            // 为表格绑定事件
            Table.api.bindevent(table);

            $('#deal-btn').click(function(){
                let allids =  Controller.api.selectedid(table);
                var selections = table.bootstrapTable('getSelections'); 
                if(allids.length==0) {
                	Toastr.error("请选择数据");
                	return 
                }
                
                //let check_flag = false
                for(let i=0;i<selections.length;i++){
                	if(selections[i].status!=0){
                		Toastr.error("存在已处理单据，请核实");
                    	return 
                	}
                	/*if(selections[i].order_list==9){
                		//盘点单
                		Fast.api.ajax({
                            url: 'outhouse/checkvouch/checkno',//检查是否存在有库存未盘点记录
                            data: {order_code:selections[i].order_code}
    	                      }, function (data) {
    	                    	  //有未扫描
    	                    	  let index = layer.confirm('存在未盘点但有库存记录，是否确定复核？', {
    	                          	  btn: ['确定','关闭'], //按钮
    	                          	  title:'温馨提示'
	    	                          }, function(index){
	    	                        	  //点确认，往下执行
	    	                        	  check_flag = true;
	    	                          }, function(index){
	    	                        	  return ;
    	                          })
    	                });
                	}*/
                }
                var lock = false;//防抖手并发
                let index = layer.confirm('确定要处理单据【'+selections[0].order_code+'】，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
              }, function(index){
                    layer.close(index);
                    let ids = Table.api.selectedids(table);
                     
                    //隐藏审核按钮，免得再次点击，重复提交
                    if (lock) {
                        return false;
                    }
                    lock = true;
                    //隐藏审核按钮，免得再次点击，重复提交
                    $("#deal-btn").addClass('hidden')

                    Fast.api.ajax({
                        url: 'inventory/temporary/setting',
                        data: {id:allids}
	                      }, function (data) {
	                    	  $("a.btn-refresh").trigger("click");
							  $("#deal-btn").removeClass('hidden')
                              lock = false;
	                      },function (data) {
	                    	  $("a.btn-refresh").trigger("click");
							  $("#deal-btn").removeClass('hidden')
                              lock = false;
	                      });
	                });
            })
            
            //查看单据
            $(document).on("click", "#view-btn", function (e, obj) {
            	let ids =  Controller.api.selectedid(table);
            	if(!ids.length){
            		Toastr.error("请选择一条记录");
            		return
            	}
            	if(ids.length!=1){
            		Toastr.error("请选择要一条记录");
            		return
            	}
            	Backend.api.open("inventory/temporary/view?ids="+ids[0],"查看单据",{area:["90%", "90%"]}) 
            })
            
            //整单删除
            $('.btn-dels').click(function(){
                let allids =  Controller.api.selectedid(table);
                if(allids.length==0) {
                	Toastr.error("请选择数据");
                	return 
                }
                
                let index = layer.confirm('确定要删除单据，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
              }, function(index){
                    layer.close(index);
                    let ids = Table.api.selectedids(table);
                     
                    //隐藏审核按钮，免得再次点击，重复提交
                    //$("#bdeal-btn").addClass('hidden')
                    Fast.api.ajax({
                        url: 'inventory/temporary/del',
                        data: {ids:allids,'dels':1}
	                      }, function (data) {
	                    	  $("a.btn-refresh").trigger("click");
	                      },function (data) {
	                    	  $("a.btn-refresh").trigger("click");
	                      });
	                });
            })
            
            //重试写回u8
            $('.btn-hand-repeat').click(function(){
            	let allids =  Controller.api.selectedid(table);
                var selections = table.bootstrapTable('getSelections'); 
                if(allids.length==0) {
                	Toastr.error("请选择数据");
                	return 
                }
                
                for(let i=0;i<selections.length;i++){
                	if(selections[i].status!=1){
                		Toastr.error("针对成功记录，才能发起重试");
                    	return 
                	}
                	if(i>0&&selections[i-1].order_code!=selections[i].order_code){
                		Toastr.error("请选择一张成功单据发起重试");
                    	return 
                	}
                }
                
                let index = layer.confirm('确定要重试复核同步金蝶数据，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
                }, function(index){
                    layer.close(index);
                    let ids = Table.api.selectedids(table);
                     
                    //隐藏审核按钮，免得再次点击，重复提交
                    //$(".btn-hand-setting").addClass('hidden')
                    Fast.api.ajax({
                        url: 'inventory/temporary/setting',
                        data: {id:ids,flag:'repeat'}
	                      }, function (data,ret) {
	                    	  $("a.btn-refresh").trigger("click");
	                      },function (data,ret) {
	                    	console.log(2,data,ret);
	                    	  //$("a.btn-refresh").trigger("click");
	                      });
	                });
                
            });
            
            
            //手动同步
            $('.btn-hand-setting').click(function(){
                let allids =  Controller.api.selectedid(table);
                var selections = table.bootstrapTable('getSelections'); 
                if(allids.length==0) {
                	Toastr.error("请选择数据");
                	return 
                }
                
                for(let i=0;i<selections.length;i++){
                	if(selections[i].status!=1){
                		Toastr.error("存在单据未复核，请核实");
                    	return 
                	}
                	if(selections[i].u8_code!=null&&selections[i].u8_code!=''){
                		Toastr.error("存在已同步KIS单据，请核实");
                    	return 
                	}
                }
                
                let index = layer.confirm('确定要同步单据？', {
                	  btn: ['确定','关闭'], //按钮
                	  title:'温馨提示'
                }, function(index){
                      layer.close(index);
                      let ids = Table.api.selectedids(table);
                       
                      //隐藏审核按钮，免得再次点击，重复提交
                      //$(".btn-hand-setting").addClass('hidden')
                      Fast.api.ajax({
                          url: 'inventory/temporary/handsetting',
                          data: {ids:ids}
  	                      }, function (data,ret) {
  	                    	  console.log(1,data,ret);
  	                    	  $("a.btn-refresh").trigger("click");
  	                      },function (data,ret) {
  	                    	console.log(2,data,ret);
  	                    	  //$("a.btn-refresh").trigger("click");
  	                      });
  	                });
                
            })
        },
        recyclebin: function () {
        	Controller.api.bindevent();
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        view: function () {
        	$('#deal-btn').click(function(){
                let index = layer.confirm('确定要处理单据，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
              }, function(index){
                    layer.close(index);
                    //隐藏审核按钮，免得再次点击，重复提交
                    $("#deal-btn").addClass('hidden')
	                    Fast.api.ajax({
	                        url: 'inventory/temporary/setting',
	                        data: {id:$("#id").val()}
	                    }, function (data) {
	                    	
	                    	  setTimeout(function(){
	                    		  $("a.btn-refresh").trigger("click");
	                    		  parent.$("a.btn-refresh").trigger("click");
	                    	  },1500)
	                    },function(){
	                    	$("#deal-btn").removeClass('hidden')
	                    });
	               	}, function(){
	                	//$("a.btn-refresh").trigger("click");
	                });
        	})
        	
        	$(document).on("click", ".btn-print", function(){
        		$(".widget-body").css("display",'none');
        	    window.print();
        	    $(".widget-body").css("display",'')
        	    Fast.api.close(); // 关闭弹窗
        	});
        	
        	$(document).on("click", ".sel_project", function(){
        		if($("#cItem").val()==''){
        			Toastr.error("请选择项目大类");
            		return
        		}else{
        			Backend.api.open("information/u8fitem/chooseproject?cItem="+$("#cItem").val(),"选择项目",{area:["75%", "80%"],offset:'r',callback:function(row){
        				$("#project_name").val(row.citemname)
        				$("#project_code").val(row.citemccode)
        			}})
        		}
        	});
        	
        	$(document).on("click", ".update_key", function(){
        		$("#edit-form").submit()
        	});
        	
        	//盘点 一键清理并重盘
        	$('#clear-re-btn').click(function(){
                let index = layer.confirm('确定要一键清理异常记录并把异常记录重新生成盘点任务，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
              }, function(index){
                    layer.close(index);
                    //隐藏审核按钮，免得再次点击，重复提交
                    $("#clear-re-btn").addClass('hidden')
	                    Fast.api.ajax({
	                        url: 'outhouse/checkvouch/oneKeyClearAndRecheck',
	                        data: {id:$("#id").val()}
	                    }, function (data) {
	                    	console.log(data)
	                    	  setTimeout(function(){
	                    		  $("a.btn-refresh").trigger("click");
	                    		  parent.$("a.btn-refresh").trigger("click");
	                    	  },300)
	                    },function(){
	                    	$("#clear-re-btn").removeClass('hidden')
	                    });
	               	}, function(){
	                	//$("a.btn-refresh").trigger("click");
	                });
        	})
        	
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                //Form.api.bindevent($("form[role=form]"));
            	Form.api.bindevent($("form[role=form]"),function(data,ret){
            		Toastr.success("操作成功");
            		$("a.btn-refresh").click()
            		return false;
            	},function(data,ret){
            		Toastr.error(ret.msg);
            		return false;
            	});
            },
            //获取选中的行
            selectedid: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row[options.pk];
                });
            },
        }
    };
    return Controller;
});

function changeCItem(index = ''){
	//后续操作
	$('#project_name_'+index).val('');
	$('#project_code_'+index).val('');
	
	if(index!==''){
		$("#cItem_name_"+index).val($("#cItem_"+index+" option:selected").text())//大类名
	}
}

function changeRdStyle(value){
	//后续操作
	if(value!==''&&value!=0){
		$('input[name="row[cRdCodeName]"]').val($('#cRdCode '+" option:selected").text())//出库类别 文本
	}
}


function toSelProject(index='',onekey=''){
	if($("#cItem_"+index).val()==''){
		Toastr.error("请选择项目大类");
		return
	}else{
		if(onekey=='onekey'&&index==''){
			if($("#project_code_").val()==''){
				Toastr.error("请选择项目");
				return
			}
			$(".citem_class").each(function(i,n){
				$("#cItem_"+i).val($("#cItem_").val())//大类编码
				$("#cItem_name_"+i).val($("#cItem_ option:selected").text())//大类名
				$("#project_name_"+i).val($("#project_name_").val())//项目名
				$("#project_code_"+i).val($("#project_code_").val())//项目编码
				$("#project_code_"+i).trigger("change");
			});
			
		}else{
			Backend.api.open("information/u8fitem/chooseproject?cItem="+$("#cItem_"+index).val(),"选择项目",{area:["75%", "80%"],offset:'r',callback:function(row){
				$("#project_name_"+index).val(row.citemname)
				$("#project_code_"+index).val(row.citemcode)
				$("#project_code_"+index).trigger("change");
			}})
		}
	}
}
$(function(){
	setTimeout(function(){
		$(".citem_class").each(function(i,n){
			$("#cItem_"+i).val($("#cItem_"+i).attr('value'))
		})
	},500)	
})
